package org.jeecg.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;

@Component
public class XszOcrUtils {
    private static final String POST_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token="+ AccessTokenUtils.getAuth();

//必传参数：id_card_side=frontfront：身份证含照片的一面 -back：身份证带国徽的一面  自动检测身份证正反面，如果传参指定方向与图片相反，支持正常识别，返回参数image_status字段为"reversed_side"
    /**
     * 识别本地图片的文字
     *
     * @param path 本地图片地址
     * @return 识别结果，为json格式
     * @throws URISyntaxException URI打开异常
     * @throws IOException        io流异常
     */
    public static Result checkFile(MultipartFile file) throws URISyntaxException, IOException {
        if (file.isEmpty()) {
            throw new NullPointerException("文件不能为空");
        }
        String image = BaseImg64Utils.getImageStrFromMultiPartFile(file);
        String param = "image=" + URLEncoder.encode(image, "UTF-8") + "&id_card_side=front"; // 确保Base64字符串被URL编码
        JSONObject jsonObject = JSON.parseObject(post(param));
        return Result.success(jsonObject);
    }

    /**
     * @param url 图片url
     * @return 识别结果，为json格式
     */
    public static String checkUrl(String url) throws IOException, URISyntaxException {
        String param = "url=" + url;
        return post(param);
    }


    /**
     * 通过传递参数：url和image进行文字识别
     *
     * @param param 区分是url还是image识别
     * @return 识别结果
     * @throws URISyntaxException URI打开异常
     * @throws IOException        IO流异常
     */
    private static String post(String param) throws URISyntaxException, IOException {
        // 开始搭建post请求
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost();
        URI url = new URI(POST_URL);
        post.setURI(url);
        // 设置请求头，请求头必须为application/x-www-form-urlencoded，因为是传递一个很长的字符串，不能分段发送
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");
        StringEntity entity = new StringEntity(param);
        post.setEntity(entity);
        HttpResponse response = httpClient.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
            String str;
            try {
                /* 读取服务器返回过来的json字符串数据 */
                str = EntityUtils.toString(response.getEntity());
                System.out.println(str);
                return str;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    public static void main(String[] args) throws URISyntaxException, IOException {
//        Result result = checkFile("D:\\sfz.jpg");
//        System.out.println("========" + result);
    }
}
